import React, { PureComponent, Fragment } from 'react'
import { Button, Upload, message, Modal, Popconfirm } from 'antd'
import { connect } from 'dva'
import {ReloadOutlined} from '@ant-design/icons';
import PateoStandardTable from '@/common/PateoTable/PateoStandardTable'
import PateoAuthButtons from '@/common/PateoAuthButtons/PateoAuthButtons'
import * as G from '@/utils/common'
import { canLogBadge } from '@/support/constant/canLog'
import { getToken } from "@/utils/common";
import styles from '../../style.less'
import { getOptAuthHeaders } from '@/utils/common'

@connect(({ common, loading }) => ({
  common,
  loading: loading.models.common,
}))

export default class CanLogTab extends PureComponent {

  state = {
    modalVisible: false,
  }

  componentDidMount() {
    this.getTableData()
  }

  // 获取表单数据
  getTableData = () => {
    const { dispatch, deviceId } = this.props
    dispatch({
      type: 'common/listDataGet',
      payload: { url: '/vehicle/canLog', vin: deviceId, page: 1, size: 2000 },
    })
  }

  // 上传日志
  uploadLog = () => {
    const { dispatch, deviceId } = this.props
    dispatch({
      type: 'common/pageablePost',
      payload: { url: '/vehicle/uploadRequest', vin: deviceId },
      callback: res => {
        if (res.statusCode === '0') {
          this.getTableData()
        }
      }
    })
  }

  //下发配置
  configDownloadRequest = () => {
    const { dispatch, deviceId } = this.props
    dispatch({
      type: 'common/pageablePost',
      payload: { url: '/vehicle/configdownloadrequest', vin: deviceId },
      callback: res => {
        if (res.statusCode === '0') {
          message.success('下发配置成功！');
        }
      }
    })
  }

  handleUpload = (info) => {
    let { fileList } = info;
    fileList = fileList.slice(-1);
    if (info.file.status === 'done' && info.file.response && info.file.response.statusCode === '200') {
      message.success(`${info.file.name} 上传成功`);
      this.setState({ modalVisible: false })
    } else if (info.file.status === 'done' && info.file.response && info.file.response.error !== '200') {
      message.error(info.file.response.statusMessage);   // 空文件提示
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 上传失败`)
    } else if (info.file.status === 'removed') {
      message.success('文件删除成功')
    }
  }

  beforeUpload = (file) => {
    if (file.type !== 'text/xml') {
      message.error('请上传xml格式的文件！');
      return false;
    }
    return true;
  }

  render() {
    const { common: { listData }, loading, deviceId, rowData } = this.props
    const carSpt = rowData.carSpt === '1' ? true : false;//是否是手机车联网车
    const domain = window.g.url;
    const url = `/vehicle/uploadfixedpathfile?vin=${deviceId}`;
    const str = `${domain}${url}`;
    const propsVinWhite = {
      action: str,
      onChange: this.handleUpload,
      multiple: false,
      headers: { "OptAuthorization": `${getToken()}`, ...getOptAuthHeaders() },
    };
    const columns = [
      {
        title: '获取时间',
        dataIndex: 'createdDt',
        width: '50%',
        render: G.dateFormatHMS,
      }, {
        title: '状态',
        dataIndex: 'status',
        width: '30%',
        render: text => canLogBadge.get(text)
      }, {
        title: '操作',
        dataIndex: 'option',
        render: (text, record) => {
          let buttons = [
            {
              title: '下载',
              key: 'download',
              onConfirm: () => window.location.href = record.fileUri,
            },
          ]
          if (record.status !== '2') buttons = []
          return <PateoAuthButtons authStr='canLog' btns={buttons} />
        },
      },
    ]
    const tableProps = {
      rowKey: 'sid',
      columns,
      dataSource: listData,
      size: 'small',
      loading,
      scroll: { y: 500 },
      pagination: false,
    }
    return (
      <Fragment>
        <div className={styles.canLog}>
          <span>上传后的文件仅保存7天,请及时保存到本地。</span>
        </div>
        <Button style={{ marginLeft: 10,marginBottom: 16 }} type="dashed" icon={<ReloadOutlined />} onClick={this.getTableData} >
          <span style={{ color: '#1C92FF' }}>刷新</span>
        </Button>
        {
          carSpt ? ''
            :
            <span>
              <Button style={{marginLeft: 10, marginBottom: 16 }} onClick={this.uploadLog} >获取log文件</Button>
              <Popconfirm title={`是否确认上传，上传配置文件将替换原有文件！`} key="d4" onConfirm={() => this.setState({ modalVisible: true })}>
                <Button style={{ marginLeft: 10, marginBottom: 16 }} type="primary">上传配置文件</Button>
              </Popconfirm>
              <Popconfirm title={`是否确认下发配置！`} key="d5" onConfirm={this.configDownloadRequest}>
                <Button style={{ marginLeft: 10, marginBottom: 16 }}>下发配置</Button>
              </Popconfirm>
            </span>
        }

        <PateoStandardTable
          tableProps={tableProps}
          fetchUrl='common/listDataGet'
          parameterUrl='/vehicle/canLog'
        />
        <Modal
          title="上传配置文件"
          visible={this.state.modalVisible}
          footer={[
            <Button key="back" type="ghost" size="default" onClick={() => this.setState({ modalVisible: false })}>返回</Button>
          ]}
          onCancel={() => this.setState({ modalVisible: false })}
        >
          <Upload
            beforeUpload={this.beforeUpload}
            {...propsVinWhite}
            accept=".xml"
            showUploadList={false}
          >{
              <Button style={{ marginLeft: 10, marginBottom: 16 }} type="primary">上传</Button>
            }
          </Upload>
        </Modal>
      </Fragment>
    )
  }
}
